<template>
  <div class="app-container">
    <div class="filter-container">
      <span class="filter-title filter-item">配置时间</span>
      <k-date-picker v-model="timeValue" class="filter-item" @hqchang="handleFilter" />
      <k-input v-model.trim="listQuery.key" class="filter-item" is-search placeholder="请输入箱子名称/关键词" :search-fun="handleFilter" @keyup.enter.native="handleFilter" />
    </div>
    <!-- openAssignAccountDialog -->

    <div class="top-right-btn-container">
      <k-button v-if="authorityHandle(41)" class="top-btn" value="添加箱子" @click.native="addBoxDialog" />
      <k-button class="top-btn" value="删除箱子" style="display:none" @click.native="deleteBox" />
      <!-- <k-button class="top-btn" value="阶段分区" @click.native="smartDivideZone" /> -->
      <k-button class="top-btn" value="对战鼓励饰品" @click.native="giveBabySettingDialog" />
      <!-- <k-button class="top-btn" value="玩法介绍" @click.native="ruleGuideDialog" /> -->
      <!-- <div class="handle-main">
        <div class="handle-item">
          <el-input v-model="userMobile" onkeyup="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入用户手机号" />
          <k-button class="top-btn" value="处理" @click.native="setDealUserData" />
        </div>
        <div class="handle-item">
          <el-input v-model="roomId" onkeyup="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入房间id" />
          <k-button class="top-btn" value="处理" @click.native="setDealRoomData" />
        </div>
      </div> -->

      <k-button class="top-right-btn" value="设置" @click.native="settingDialog" />
    </div>

    <!--表格相关 -->
    <el-table
      ref="dragTable"
      :data="boxList"
      fit
      border
      highlight-current-row
      row-key="id"
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{ background: '#F6F5FA', color: '#4E4F62' }"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
    >
      <!-- <el-table-column min-width="60px" type="selection" align="center" /> -->
      <el-table-column width="60px" label="序号" type="index" align="center" />
      <el-table-column min-width="110px" label="箱子图标" align="center">
        <template slot-scope="scope">
          <el-image style="width: 110px; height: 80px" :src="scope.row.imgUrl" :preview-src-list="[scope.row.imgUrl]" fit="contain" />
        </template>
      </el-table-column>
      <el-table-column prop="boxName" min-width="100px" label="箱子名称" show-overflow-tooltip align="center" />
      <el-table-column prop="rebate" min-width="80px" label="箱子折扣(%)" align="center" />
      <el-table-column prop="price" min-width="80px" label="箱子价格(R)" sortable="custom" align="center" />
      <el-table-column prop="percentUser" min-width="90px" label="即时进价" align="center" />
      <el-table-column
        prop="percentFission"
        min-width="90px"
        label="历史进价"
        align="center"
      />
      <!-- <el-table-column prop="percentFission" min-width="90px" label="主播通道利润" align="center" /> -->
      <el-table-column prop="fistStagePrice" min-width="80px" label="第一阶段期望价格" align="center" />
      <el-table-column min-width="100px" label="饰品展示缩略图" align="center">
        <template slot-scope="scope">
          <el-image style="width: 90px; height: 80px" :src="scope.row.goodsImgUrl" fit="contain" :preview-src-list="[scope.row.goodsImgUrl]" />
        </template>
      </el-table-column>
      <el-table-column prop="assembleTime" min-width="110px" label="配置时间" align="center" />
      <el-table-column min-width="110px" label="箱子状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.boxStatus"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="上架"
            inactive-text="下架"
            :active-value="1"
            :inactive-value="2"
            :disabled="!authorityHandle(41)"
            @change="boxOnlineState($event, scope)"
          />
        </template>
      </el-table-column>
      <el-table-column min-width="200px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <k-button class="table-btn" value="修改箱子" @click.native="addBoxUpdateDialog(scope.row)" />
            <!-- <k-button class="table-btn" value="晶粹配置" @click.native="bulletSettingDialog(scope.row)" /> -->
            <k-button class="table-btn" value="配置饰品" @click.native="configBabyLib(scope.row.id, 41)" />
            <!-- :disabled="scope.row.boxStatus === 1 ? true : false" -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="totalRows > 0" :total="totalRows" :page.sync="listQuery.pager.pageNo" :limit.sync="listQuery.pager.pageSize" @pagination="loadData" />
    <!-- 添加箱子 addBox 弹窗 -->
    <k-dialog
      :show-hide.sync="addBox.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      class="addBox-dialog"
      :title="textMap[dialogStatus]"
      :show-foot="false"
      :two-btn="true"
      :close-fun="handleCloseDialog"
      @click="saveBoxDataEvent"
    >
      <el-radio-group v-model="boxType" fill="#3b425d" text-color="#ffffff" class="top-radio-group">
        <el-radio-button label="addBox">添加箱子</el-radio-button>
        <el-radio-button label="customBox">自定义箱子</el-radio-button>
      </el-radio-group>
      <!-- 这里参考用户通道 -->
      <div class="dialog-giveBabySetting">
        <div v-if="boxType === 'addBox'" style="padding:20px;margin-left:50px">
          <label>普通箱子：</label>
          <el-select v-model="boxValueModel" multiple style="width: 70%;" filterable placeholder="请选择">
            <el-option v-for="item in resultOpList" :key="item.lineId" :label="item.lineName" :value="item.lineId" @click.native="selectChange(item)" />
          </el-select>
          <div style="margin-top:10px;margin-bottom:200px">
            <el-tag v-for="(item, index) of checkedBoxsList" :key="item.lineId" closable @close="handleBabyTagDelete(index)">{{ item.lineName }}</el-tag>
          </div>
        </div>
        <div v-else style="padding:50px;">
          <el-form :model="addBoxInfo" label-width="auto" class="form-modify">
            <el-form-item label="箱子名称：" prop="name"><el-input v-model="addBoxInfo.boxName" show-word-limit placeholder="请输入饰品名称" /></el-form-item>
            <el-form-item label="选择类别：" prop="name">
          <el-select v-model="addBoxInfo.levelId" placeholder="请选择">
          <el-option
            v-for="item in selectCategoryOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        </el-form-item>
            <el-form-item label="箱子图标：">
              <k-upload-file ref="upload1" v-model="addBoxInfo.imgUrl" upload-style="img" @successUpload="successUpload($event, 0)" />
              <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </k-dialog>

    <!-- addBox 修改弹窗 -->
    <k-dialog
      :show-hide.sync="addBoxUpdate.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      class="addBox-dialog"
      title="修改箱子"
      :show-foot="false"
      :two-btn="authorityHandle(41)"
      @click="saveBoxDataEvent"
    >
      <el-form :model="addBoxInfo" label-width="auto" class="form-modify">
        <el-form-item label="箱子名称：" prop="name">
          <el-input v-model="addBoxInfo.boxName" :readonly="!authorityHandle(41)" show-word-limit placeholder="请输入箱子名称" />
        </el-form-item>
        <el-form-item label="选择类别：">
          <el-select v-model="addBoxInfo.levelId" placeholder="请选择">
          <el-option
            v-for="item in selectCategoryOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="箱子图标：">
          <k-upload-file ref="upload1" v-model="addBoxInfo.imgUrl" upload-style="img" @successUpload="successUpload($event, 0)" />
          <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
        </el-form-item>
        <el-form-item label="饰品展示缩略图：" prop="iconUrl">
          <k-upload-file ref="upload2" v-model="addBoxInfo.goodsImgUrl" upload-style="img" @successUpload="successUpload($event, 1)" />
          <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
        </el-form-item>
      </el-form>
    </k-dialog>
    <!-- 智能阶段分区 弹窗 -->
    <k-dialog
      :show-hide.sync="smartDivideZoneDialog"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="阶段分区"
      :show-foot="false"
      :two-btn="authorityHandle(41)"
      @click="saveSmartDivideZone"
    >
      <div class="dialog-DivideZone">
        <ul>
          <li v-for="(divideZoneItem, index) in divideZone.divideZoneArray" :key="divideZoneItem.id">
            <span class="warning-title">阶段{{ index + 1 }}:</span>
            <span class="warning-title">溢出箱价:</span>
            <el-input v-model.number="divideZoneItem.minPercent" :readonly="!authorityHandle(41)" class="price-input" />
            <i style="margin: 0 3px;">—</i>
            <el-input v-model.number="divideZoneItem.maxPercent" :readonly="!authorityHandle(41)" class="price-input" />

            <i v-if="authorityHandle(41)" v-show="index != 0" class="el-icon-remove" @click="removeDivideZoneItem(divideZoneItem.id, index)" />
            <i v-if="authorityHandle(41)" v-show="index === divideZone.divideZoneArray.length - 1" class="el-icon-circle-plus" @click="addDivideZoneItem(index)" />
          </li>
        </ul>
      </div>
    </k-dialog>
    <!-- 赠送饰品配置 弹窗 -->
    <k-dialog
      :show-hide.sync="giveBabySetting.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="对战鼓励饰品"
      class="give-dialog"
      :two-btn="authorityHandle(41)"
      :close-fun="giveBabyCloseDialog"
      @click="saveGiveBabyData"
    >
      <el-form label-width="auto" class="give_div">
        <el-form-item label="饰品名称：">
          <el-select v-model="goodsValueModel" multiple style="width: 100%;" filterable placeholder="请选择" :disabled="!authorityHandle(41)" @change="selectGiveBabyChange">
            <el-option v-for="item in giveGoodsResultList" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
          </el-select>
        </el-form-item>
      </el-form>
    </k-dialog>
    <!-- 晶粹配置 弹窗 -->
    <k-dialog
      :show-hide.sync="bulletSetting"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="晶粹配置"
      class-name="creatRollRoom_dialog"
      :show-foot="false"
      :two-btn="authorityHandle(41)"
      @click="saveBulletSetting"
    >
      <div class="set_box">
        <div v-for="(item, index) in bulletSettingItemList" :key="item.id" class="Recharge_Data">
          <div class="Recharge_Data_box">
            <span>晶粹数量:</span>
            <el-input v-model.trim="item.minAmmo" :readonly="!authorityHandle(41)" />
            <i style="margin: 0 2px;">—</i>
            <el-input v-model.trim="item.maxAmmo" :readonly="!authorityHandle(41)" style="margin-right:20px" />
            <span>掉落概率:</span>
            <el-input v-model.trim="item.probability" :readonly="!authorityHandle(41)" />
            %
          </div>
          <div class="operation">
            <i v-if="authorityHandle(41)" v-show="index != 0" class="el-icon-remove" @click="deleteItem(item.id, index)" />
            <i v-if="authorityHandle(41)" v-show="index == bulletSettingItemList.length - 1" class="el-icon-circle-plus" @click="newlyAdded()" />
          </div>
        </div>
        <span>预期晶粹掉落数量：{{ getExpectedBulletNums() }}</span>
      </div>
    </k-dialog>
    <!-- 设置 弹窗 -->
    <k-dialog
      :show-hide.sync="battleSetting"
      :modal-append-to-body="false"
      :append-to-body="true"
      class="setting_dialog"
      title="设置"
      :two-btn="authorityHandle(41)"
      @click="saveSettingDialog"
    >
      <el-radio-group v-model="settingType" fill="#3b425d" text-color="#ffffff" class="top-radio-group">
        <!-- <el-radio-button label="robotBoxSetting">AI开箱设置</el-radio-button> -->
        <el-radio-button label="otherSetting">相关限制</el-radio-button>
        <!-- <el-radio-button label="consecutiveSetting">对战连败设置</el-radio-button> -->
      </el-radio-group>
      <div v-if="settingType === 'robotBoxSetting'" class="dialog-warningSetting">
        <ul>
          <li>
            <span class="warning-title">箱子名称:</span>
            <el-select v-model="unusefullModel" disabled placeholder="全部" />
            <span class="warning-title">开箱数量:</span>
            <el-input v-model.number="normalAiValueModel.openCount" :readonly="!authorityHandle(41)" class="price-input" />
            <span class="warning-title">开箱AI:</span>
            <el-select v-model="normalAiValueModel.userId" :disabled="!authorityHandle(41)" filterable placeholder="请选择">
              <el-option v-for="item in robotResultList" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
            </el-select>
          </li>
        </ul>
        <ul>
          <li v-for="(specialAiItem, index) in specialAiValueModelList" :key="index" class="noTitle" :class="{ hasTitle: index === 0 }">
            <span class="warning-title">箱子名称:</span>
            <el-select v-model="specialAiItem.boxId" :disabled="!authorityHandle(41)" filterable placeholder="请选择">
              <el-option v-for="item in boxResultList" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
            </el-select>
            <span class="warning-title">开箱数量:</span>
            <el-input v-model.number="specialAiItem.openCount" :readonly="!authorityHandle(41)" class="price-input" />
            <span class="warning-title">开箱AI:</span>
            <el-select v-model="specialAiItem.userId" :disabled="!authorityHandle(41)" filterable placeholder="请选择">
              <el-option v-for="item in robotResultList" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
            </el-select>
            <i v-if="authorityHandle(41)" v-show="index != 0" class="el-icon-remove" @click="removeAiItem(index)" />
            <i v-if="authorityHandle(41)" v-show="index === specialAiValueModelList.length - 1" class="el-icon-circle-plus" @click="addAiItem(index)" />
          </li>
        </ul>
      </div>
      <div v-if="settingType === 'otherSetting'" class="othersetting_div">
        <el-form :model="relatedLimit" label-width="auto" class="form-modify">
          <el-form-item label="对战门槛（积分）："><el-input v-model="relatedLimit.minPrice" :readonly="!authorityHandle(41)" placeholder="请输入" /></el-form-item>
          <div style="display:flex;">
            <el-form-item label="同时对战上限："><el-input v-model="relatedLimit.maxCount" :readonly="!authorityHandle(41)" placeholder="请输入" /></el-form-item>
            <el-form-item label="进出房间时间限制：" style="margin-left:20px">
              <el-input v-model="relatedLimit.minTime" :readonly="!authorityHandle(41)" placeholder="请输入" />
            </el-form-item>
            <span class="second">秒</span>
          </div>
          <div style="display:flex">
            <el-form-item label="对战箱子上限："><el-input v-model="relatedLimit.maxBoxTypeCount" :readonly="!authorityHandle(41)" placeholder="请输入" /></el-form-item>
            <el-form-item label="对战箱子数量上限：" style="margin-left:20px">
              <el-input v-model="relatedLimit.maxBoxNum" :readonly="!authorityHandle(41)" placeholder="请输入" />
            </el-form-item>
          </div>
          <div style="display:flex">
            <el-form-item>
              <span slot="label">
                <el-tooltip content="这个时间是限制用户在几个小时内:“加入”或“创建”房间的次数, 配合后面的数量一起限制" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                时间（小时）
              </span>
              <el-input v-model="relatedLimit.joinLimitIntervalHour" style="width:90%" :readonly="!authorityHandle(41)" placeholder="请输入">
                <span slot="suffix" class="second">小时</span>
              </el-input>
            </el-form-item>
            <!--  -->
            <el-form-item label="数量(次数)：" style="margin-left:20px">
              <el-input v-model="relatedLimit.joinLimitNum" :readonly="!authorityHandle(41)" placeholder="请输入" />
            </el-form-item>
          </div>
        </el-form>
        <div class="radiodiv">
          <el-checkbox v-model="relatedLimit.fissionCouldUser" :disabled="!authorityHandle(41)">主播不可加入玩家对战房</el-checkbox>
          <!-- <el-checkbox v-model="relatedLimit.robotCouldUser" :disabled="!authorityHandle(41)">AI不可加入玩家对战房</el-checkbox> -->
          <!-- <el-checkbox v-model="relatedLimit.fissionCouldRobot" :disabled="!authorityHandle(41)">主播不可加入AI对战房</el-checkbox> -->
        </div>
      </div>

      <div v-if="settingType === 'consecutiveSetting'" class="othersetting_div">
        <div class="consecutive" style="display:flex;">
          <el-form label-width="auto" class="form-modify">
            <el-form-item label="最少连败数量：">
              <el-input v-model="mostDefeatNum[0]" onkeyup="value=value.replace(/[^0-9.]/g,'')" :readonly="!authorityHandle(41)" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="最多连败数量：">
              <el-input v-model="mostDefeatNum[1]" onkeyup="value=value.replace(/[^0-9.]/g,'')" :readonly="!authorityHandle(41)" placeholder="请输入" />
            </el-form-item>
          </el-form>

        </div>
      </div>
    </k-dialog>
    <!-- 玩法介绍 弹窗 -->
    <k-dialog
      :show-hide.sync="ruleGuide.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="玩法介绍"
      class-name="ruleGuide-dialog"
      :show-foot="false"
      :two-btn="authorityHandle(41)"
      @click="guideSave"
    >
      <div class="dialog-ruleGuide" style="padding:30px">
        <el-form :model="ruleGuideContent" label-width="auto">
          <el-form-item label="内容介绍：" prop="content">
            <quill-editor ref="myQuillEditor" v-model.trim="ruleGuideContent.content" :options="editorOption" class="editer" />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>
  </div>
</template>

<script>
import {
  setBattleDescribe,
  getBattleDescribe,
  ListBoxData,
  getGeneralList,
  addBoxToBattle,
  saveBoxData,
  updateBoxData,
  getOtherGoodsList,
  setOtherGoodsList,
  getGoodsPlatformList,
  getBattleSetting,
  setBattleSetting,
  getBattleRobot,
  updateBoxUpStatus,
  setBattleRobot,
  getBattleBoxList,
  getBattleRobotList,
  updateBoxSort,
  dealUserData,
  dealRoomData,
  getFalseCount,
  setFalseCount
} from '@/api/battel/index'
import { getAmmoBoxList, setAmmoBoxList,getBoxLeveSetting } from '@/api/bullet/index'
import { getBoxStageList, setBoxStageList } from '@/api/rules/listdata'

import Pagination from '@/components/Pagination'
import Sortable from 'sortablejs'
import { setBattleCompetition, removeBattleCompetition, getBattleCompetition } from '@/utils/auth'
export default {
  components: { Pagination },
  data() {
    return {
      mostDefeatNum: [], // 最多连败数量
      currentUserId: -1,
      relatedLimit: {
        minPrice: undefined, // 对战门槛',
        maxCount: undefined, // 同时对战上限',
        joinLimitIntervalHour: undefined, // 限制多久之内房间数量',
        joinLimitNum: undefined, // /数量',
        minTime: undefined, // 进出房间时间限制',
        maxBoxTypeCount: undefined, // 对战箱子种类上限',
        maxBoxNum: undefined, // 对战箱子数量上限',
        fissionCouldUser: false, // 主播是否可加入玩家',
        robotCouldUser: false, // AI是否可加入玩家',
        fissionCouldRobot: false // 主播是否可加入AI'
      },
      unusefullModel: undefined,
      normalAiValueModel: {
        id: undefined,
        boxId: -1, // 箱子id',
        openCount: undefined, // 开箱数量',
        userId: undefined // 开箱AIid'
      },
      specialAiValueModelList: [
        {
          boxId: undefined, // 箱子id',
          openCount: undefined, // 开箱数量',
          userId: undefined // 开箱AIid'
        }
      ],
      checkList: [],
      robotResultList: [],
      boxResultList: [],
      giveGoodsResultList: [],
      checkedGiveBabyList: [],
      goodsValueModel: [],
      boxValueModel: [],
      resultOpList: [],
      checkedBoxsList: [],
      boxType: 'addBox',
      settingType: 'otherSetting',
      currentBoxId: undefined,
      bulletSettingItemList: [
        {
          id: undefined,
          boxId: undefined,
          minAmmo: undefined,
          maxAmmo: undefined,
          probability: undefined
        }
      ],
      divideZone: {
        divideZoneArray: [
          {
            id: undefined,
            boxId: -2,
            minPercent: '',
            maxPercent: '',
            openSort: 0
          }
        ]
      },
      multipleSelection: [],
      addBoxInfo: {
        id: '', // 保存箱子配置时必传",
        imgUrl: '', // 箱子图标",
        goodsImgUrl: '', // 饰品展示缩略图",
        boxName: '', // 箱子名称",
        levelId:'' // 选择类别

      },
      selectCategoryOptions:[],// 选择类别下拉框
      boxList: [],
      totalRows: 0, // 分页组件--数据总条数
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10,
          totalRows: '',
          start: ''
        },
        sort: '', // 排序字段 为对应列名,
        direction: '', // 排序 正向(asc)逆向(desc),
        boxType: undefined, // //走不同方法 不需要前端传递",
        startTime: undefined, // 饰品外观',
        endTime: undefined, // 饰品类别',
        key: '' // 箱子名称或关键词 箱子配置界面所用'
      },
      timeValue: '',
      conditions: {
        keyword: null
      },
      addBox: {
        showHide: false
      },
      addBoxUpdate: {
        showHide: false
      },
      giveBabySetting: {
        showHide: false
      },
      ruleGuide: {
        showHide: false
      },
      ruleGuideContent: {
        content: ''
      },
      editorOption: {
        //  富文本编辑器配置
        placeholder: '请输入内容',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            [{ script: 'sub' }, { script: 'super' }], // 上下标
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ direction: 'rtl' }], // 文本方向
            [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ font: [] }], // 字体
            [{ align: [] }], // 对齐方式
            ['clean'], // 清除字体样式
            ['image'] // 上传图片、上传视频
          ]
        }
      },
      bulletSetting: false,
      battleSetting: false,
      smartDivideZoneDialog: false,
      dialogStatus: 'create',
      textMap: {
        update: '修改箱子',
        create: '添加箱子'
      },
      userMobile: '',
      roomId: ''
    }
  },
  watch: {
    // 时间赋值
    timeValue(val) {
      this.listQuery.startTime = this.timeValue ? this.timeValue[0] : null
      this.listQuery.endTime = this.timeValue ? this.timeValue[1] : null
    }
  },
  created() {
    this.loadData()
    this.getSmartDivideZone()
    this.getGeneralDescribe()
  },
  methods: {
    setDealUserData() {
      if (!this.userMobile || this.userMobile.length != 11) {
        this.$message.error('用户手机号格式错误')
        return
      }
      dealUserData({ mobile: this.userMobile }).then(res => {
        this.$message.success('操作成功')
      })
    },

    setDealRoomData() {
      if (!this.roomId) {
        this.$message.error('请输入房间ID')
        return
      }
      dealRoomData({ roomId: this.roomId }).then(res => {
        this.$message.success('操作成功')
      })
    },

    loadData() {
      if (getBattleCompetition()) {
        this.listQuery = getBattleCompetition()
        if (getBattleCompetition().startTime && getBattleCompetition().endTime) this.timeValue = [getBattleCompetition().startTime, getBattleCompetition().endTime]
      }
      ListBoxData(this.listQuery).then(res => {
        const data = res.data
        this.totalRows = data.totalRows
        this.boxList = data.rows
        // let list = []
        // for(let i=0;i<data.rows.length;i++){
        // 	data.rows[i].zone_sort = i
        // 	list.push(data.rows[i])
        // }
        // this.boxList = list

        this.$nextTick(() => {
          this.setSort()
        })
        removeBattleCompetition()
      })
    },

    setSort() {
      return
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.boxList.splice(evt.oldIndex, 1)[0]
          this.boxList.splice(evt.newIndex, 0, targetRow)
          this.boxList.map((item, index) => {
            item.zoneSort = index
          })
          const list = []
          for (let i = 0; i < this.boxList.length; i++) {
            const item = {
              id: this.boxList[i].id
            }
            if (this.listQuery.pager.pageNo > 1) {
              item.zoneSort = String(this.listQuery.pager.pageNo - 1) + this.boxList[i].zoneSort
            } else {
              item.zoneSort = this.boxList[i].zoneSort
            }
            list.push(item)
          }
          // 等级箱子列表页更新排序
          updateBoxSort(list).then(res => {
            this.$log(res)
            this.loadData()
          })
        }
      })
    },

    checkboxGroupChange(v) {
      this.$log(v)
    },
    // 箱子上架
    boxOnlineState(event, scope) {
      const id = scope.row.id
      updateBoxUpStatus({ id: id }).then(res => {
        const isOk = res.data.success
        if (isOk) {
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.data.msg)
          scope.row.boxStatus = 1
        }
      })
    },
    // 请求赠送全部饰品
    getGoodsPlatformList() {
      getGoodsPlatformList({ key: '', alreadyIds: '[-1]' }).then(res => {
        this.giveGoodsResultList = []
        Object.assign(this.giveGoodsResultList, res.data)
      })
    },
    async addBoxDialog() {
      this.$resetForm(this.addBoxInfo)
      this.checkedBoxsList = []
      getGeneralList().then(res => {
        this.resultOpList = res.data
      })
      const res = await getBoxLeveSetting()
      this.selectCategoryOptions = res.data || []
      this.addBox.showHide = true
    },
    // 箱子选择事件
    selectChange(item) {
      const itemIndex = this.checkedBoxsList.findIndex(v => {
        return v.lineId === item.lineId
      })
      if (itemIndex === -1) {
        this.checkedBoxsList.push(item)
      } else {
        this.checkedBoxsList.splice(itemIndex, 1)
      }
      // this.$log(this.checkedBoxsList)
    },
    // 添加箱子
    saveBoxDataEvent() {
      setBattleCompetition(this.listQuery)
      if (this.addBoxUpdate.showHide) {
        // 修改自定义箱子
        updateBoxData(this.addBoxInfo).then(res => {
          if (res.data.success) {
            this.$message.success('保存成功')
            this.handleFilter()
          } else {
            this.$message.error(res.data.msg)
          }
          this.$resetForm(this.addBoxInfo)
          this.addBoxUpdate.showHide = false
        })
      } else {
        // 添加普通箱子
        if (this.boxType === 'addBox') {
          const tempList = this.checkedBoxsList.map(item => {
            return item.lineId
          })
          addBoxToBattle(tempList).then(res => {
            if (res.data.success) {
              this.$message.success('保存成功')
              this.handleFilter()
            } else {
              this.$message.error(res.data.msg)
            }
            this.addBox.showHide = false
            this.addBoxUpdate.showHide = false
          })
        } else {
          // 添加自定义箱子
          saveBoxData(this.addBoxInfo).then(res => {
            if (res.data.success) {
              this.$message.success('保存成功')
              this.handleFilter()
            } else {
              this.$message.error(res.data.msg)
            }
            this.$resetForm(this.addBoxInfo)
            this.addBox.showHide = false
          })
        }
      }
    },
    handleBabyTagDelete(index) {
      this.checkedBoxsList.splice(index, 1)
      this.boxValueModel.splice(index, 1)
    },
    ruleGuideDialog() {
      this.ruleGuide.showHide = true
    },
    // 保存玩法管理
    guideSave() {
      setBattleCompetition(this.listQuery)
      setBattleDescribe({ data: this.ruleGuideContent.content }).then(res => {
        this.$message.success('保存成功')
        this.ruleGuide.showHide = false
      })
    },
    // 加载玩法管理
    getGeneralDescribe() {
      getBattleDescribe().then(res => {
        this.ruleGuideContent.content = res.data
      })
    },
    removeAiItem(index) {
      this.specialAiValueModelList.splice(index, 1)
    },
    addAiItem(index) {
      this.specialAiValueModelList.push({
        boxId: undefined,
        openCount: undefined,
        userId: undefined
      })
    },
    // visibleChange($event, value) {
    //   if ($event) {
    //     this.$log(value)
    //     this.currentUserId = value
    //   }
    // },
    // // 过滤选择AI
    // selectRobotChange(value) {
    //   if (this.currentUserId !== value) {
    //     this.robotResultList.map(item => {
    //       if (item.lineId === this.currentUserId) {
    //         item.lineCheck = false
    //       }
    //     })
    //   }
    //   this.robotResultList.map(item => {
    //     if (item.lineId === value) {
    //       item.lineCheck = true
    //     }
    //   })
    //   // this.robotResultList.splice(this.robotResultList.findIndex(item => item.lineId === value), 1)
    // },
    // 保存设置  AI配置
    saveSettingDialog() {
      setBattleCompetition(this.listQuery)
      if (this.settingType === 'robotBoxSetting') {
        this.specialAiValueModelList.unshift(this.normalAiValueModel)
        this.$log(this.specialAiValueModelList)
        setBattleRobot(this.specialAiValueModelList).then(res => {
          this.$message.success('保存成功')
          this.battleSetting = false
        })
      } else if (this.settingType === 'otherSetting') {
        this.$log(this.relatedLimit)
        setBattleSetting(this.relatedLimit).then(res => {
          this.$message.success('保存成功')
          this.battleSetting = false
        })
      } else if (this.settingType === 'consecutiveSetting') {
        if (!this.mostDefeatNum) {
          this.$message.error('请输入数量')
          return
        }
        // if (this.mostDefeatNum[0] > this.mostDefeatNum[1]) {
        //   this.$message.error('最少连败数量不能大于最多连败数量：')
        //   return
        // }
        setFalseCount({ count: Number(this.mostDefeatNum[0]), otherCount: Number(this.mostDefeatNum[1]) }).then(res => {
          this.$message.success('保存成功')
          this.battleSetting = false
        })
      }
    },
    // 设置弹窗
    settingDialog() {
      getBattleRobotList().then(res => {
        this.robotResultList = res.data
        this.battleSetting = true
        // 获取配置
        getBattleRobot().then(res => {
          const obj = res.data
          if (obj.length > 0) {
            // obj.map(objitem => {
            //   this.robotResultList.map(item => {
            //     if (item.lineId === objitem.userId) {
            //       item.lineCheck = true
            //     }
            //   })
            // })
            this.normalAiValueModel = obj.shift() // 删除返回的第一个元素
            this.specialAiValueModelList = obj
          }
        })
      })
      getBattleBoxList().then(res => {
        this.boxResultList = res.data
      })
      getBattleSetting().then(res => {
        if (res.data) {
          this.relatedLimit = res.data
        }
      })
      getFalseCount().then(res => {
        this.mostDefeatNum = res.data
      })
    },
    // 设置新增
    newlyAdded() {
      this.bulletSettingItemList.push({
        id: undefined,
        boxId: undefined,
        minAmmo: undefined,
        maxAmmo: undefined,
        probability: undefined
      })
    },
    // 设置删除
    deleteItem(value, indexItem) {
      if (!value) {
        this.bulletSettingItemList.splice(indexItem, 1)
        return
      }
      var index = this.bulletSettingItemList.findIndex(function(item) {
        return item.id === value
      })
      if (index !== -1) {
        this.bulletSettingItemList.splice(index, 1)
      }
    },

    removeDivideZoneItem(value) {
      const index = this.divideZone.divideZoneArray.findIndex(function(item) {
        return item.id === value
      })
      if (index !== -1) {
        this.divideZone.divideZoneArray.splice(index, 1)
      }
      this.divideZone.divideZoneArray.map((item, index) => {
        item.openSort = index
      })
    },
    addDivideZoneItem(index) {
      this.divideZone.divideZoneArray.push({
        id: undefined,
        boxId: -2,
        minPercent: '',
        maxPercent: '',
        openSort: index + 1
      })
    },
    getSmartDivideZone() {
      getBoxStageList({ id: -2 }).then(res => {
        this.divideZone.divideZoneArray = res.data
        if (res.data.length === 0) {
          this.addDivideZoneItem(0)
        }
      })
    },
    saveSmartDivideZone() {
      setBattleCompetition(this.listQuery)
      this.divideZone.divideZoneArray.map(item => {
        item.boxId = -2
      })
      setBoxStageList(this.divideZone.divideZoneArray).then(res => {
        if (res.data.success) {
          this.$message.success('保存成功')
          this.smartDivideZoneDialog = false
          this.loadData()
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 智能分区
    smartDivideZone() {
      this.smartDivideZoneDialog = true
    },
    selectGiveBabyChange(value) {
      this.checkedGiveBabyList = value
    },
    // 保存赠送饰品配置 数据
    saveGiveBabyData() {
      setBattleCompetition(this.listQuery)
      Object.assign(this.checkedGiveBabyList, this.goodsValueModel)
      setOtherGoodsList(this.checkedGiveBabyList).then(res => {
        this.$message.success('保存成功')
        this.giveBabySetting.showHide = false
      })
    },
    // 对战鼓励饰品
    giveBabySettingDialog() {
      this.getGoodsPlatformList()
      getOtherGoodsList().then(res => {
        this.goodsValueModel = res.data
      })
      this.giveBabySetting.showHide = true
    },
    giveBabyCloseDialog() {
      this.giveBabySetting.showHide = false
    },

    // 选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 表格的排序条件发生变化的时候会触发该事件
    sortChange(column, prop, order) {
      this.listQuery.sort = column.prop
      if (column.order === 'ascending') {
        this.listQuery.direction = 'asc'
      } else if (column.order === 'descending') {
        this.listQuery.direction = 'desc'
      }
      this.loadData()
    },
    // 搜索查询事件
    handleFilter() {
      this.listQuery.pager.pageNo = 1
      this.loadData()
    },
    // 删除箱子
    // deleteBox() {
    //   const _vue = this
    //   if (_vue.multipleSelection.length < 1) {
    //     this.$message.error('请至少选择一条数据进行删除！')
    //     return
    //   }
    //   const selections = _vue.multipleSelection
    //   this.$confirm('确定删除选中的箱子么?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     var ids = []
    //     for (var i = 0; i < selections.length; i++) {
    //       ids.push(selections[i].id)
    //     }
    //     deleteGeneralData({ ids: ids }).then(res => {
    //       if (res.data.success) {
    //         this.$message.success('删除成功')
    //         this.loadData()
    //       } else {
    //         this.$message.error(res.data.msg)
    //       }
    //     })
    //   }).catch(() => {
    //     this.$message({
    //       type: 'info',
    //       message: '已取消'
    //     })
    //   })
    // },

    getExpectedBulletNums() {
      const expectBulletNums = this.bulletSettingItemList
        .map(item => {
          return ((Number(item.minAmmo) + Number(item.maxAmmo)) / 2) * item.probability
        })
        .reduce(function(a, b) {
          return Number(a) + Number(b)
        })
      // this.$log('---', expectBulletNums)
      return expectBulletNums / 100
    },
    saveBulletSetting() {
      setBattleCompetition(this.listQuery)
      const probSum = this.bulletSettingItemList
        .map(item => {
          return item.probability
        })
        .reduce(function(a, b) {
          return Number(a) + Number(b)
        })
      this.$log(probSum)
      if (100 - Number(probSum).toFixed(2) !== 0) {
        this.$message.error('掉落概率和要等于100,还需要 ' + (100 - probSum).toFixed(2))
        return
      }
      this.bulletSettingItemList.map(item => {
        item.boxId = this.currentBoxId
      })
      setAmmoBoxList(this.bulletSettingItemList).then(res => {
        this.$message.success('保存成功')
        this.bulletSetting = false
      })
    },
    bulletSettingDialog(row) {
      this.bulletSetting = true
      this.currentBoxId = row.id
      getAmmoBoxList({ boxId: row.id }).then(res => {
        this.bulletSettingItemList = res.data
      })
    },
    async addBoxUpdateDialog(row) {
      this.addBoxUpdate.showHide = true
      this.addBoxInfo.id = row.id
      this.addBoxInfo.boxName = row.boxName
      this.addBoxInfo.imgUrl = row.imgUrl
      this.addBoxInfo.goodsImgUrl = row.goodsImgUrl
      this.addBoxInfo.levelId =row.levelId
      const res = await getBoxLeveSetting()
      this.selectCategoryOptions = res.data || []
    },
    successUpload(data, flag) {
      if (flag === 0) {
        this.addBoxInfo.imgUrl = data
      } else {
        this.addBoxInfo.goodsImgUrl = data
      }
    },

    handleCloseDialog() {
      this.$resetForm(this.addBoxInfo)
      this.addBox.showHide = false
    },
    // 跳转配置饰品
    configBabyLib(boxid, permissionid) {
      setBattleCompetition(this.listQuery)
      this.$router.push({ path: '/rootplayrules/config-babylibnew', query: { id: boxid, permissionid }})
    }
  }
}
</script>
<style lang="scss" scoped>
$menuText: #14162e; // 侧边栏字体颜色
$hoverColor: #1D143C; // 鼠标停留主色调浅色
$mainColor: #3b425d; // 主色调
.consecutive {
	width: 736px;
}
.dialog-DivideZone {
	::v-deep.el-input {
		width: 110px;
	}
	.price-input {
		width: 150px;
	}
	.el-icon {
		&-circle-plus,
		&-remove {
			font-size: 22px;
			color: #3b425d;
			margin-left: 10px;
		}
	}
	ul {
		list-style-type: none;
		margin: 0;
		padding: 0;
		li {
			margin: 0 0 30px 0px;
			display: flex;
			flex-direction: row;
			align-items: center;
			.warning-title {
				font-size: 16px;
				color: $menuText;
				margin-right: 10px;
				margin-left: 20px;
			}
			i {
				color: #d1d5dd;
			}
			&.noTitle {
				&:before {
					display: block;
					width: 80px;
					content: '';
				}
			}
			&.hasTitle {
				&:before {
					font-weight: 700;
					color: $menuText;
					content: '特殊AI配置:';
				}
			}
		}
	}
}
.dialog-warningSetting {
	::v-deep.el-input {
		width: 150px;
	}
	.price-input {
		width: 110px;
	}
	.el-icon {
		&-circle-plus,
		&-remove {
			font-size: 22px;
			color: #3b425d;
			margin-left: 10px;
		}
	}
	ul {
		list-style-type: none;
		margin: 0;
		padding: 0;
		&:first-child {
			li {
				&:first-child {
					&:before {
						content: '常规AI配置:';
						width: 80px;
						font-weight: 700;
						color: $menuText;
						display: block;
					}
				}
			}
		}
		li {
			margin: 0 0 30px 0px;
			display: flex;
			flex-direction: row;
			align-items: center;
			.warning-title {
				font-size: 16px;
				color: $menuText;
				margin-right: 10px;
				margin-left: 20px;
			}
			i {
				color: #d1d5dd;
			}
			&.noTitle {
				&:before {
					display: block;
					width: 80px;
					content: '';
				}
			}
			&.hasTitle {
				&:before {
					font-weight: 700;
					color: $menuText;
					content: '特殊AI配置:';
				}
			}
		}
	}
}
.editer {
	width: 500px;
	border-radius: 8px;
	float: left;
	box-sizing: border-box;
	color: #606266;
	::v-deep .ql-container {
		height: 400px;
		border-radius: 0px 0px 8px 8px;
	}
	::v-deep .ql-toolbar.ql-snow {
		border-radius: 8px 8px 0px 0px;
	}
}

.radiodiv {
	display: flex;
	flex-direction: column;
	margin-left: 120px;
	.el-checkbox {
		width: 200px;
		margin-top: 20px;
	}
}
.second {
	line-height: 40px;
	margin-left: 10px;
}
.filter-container {
	width: 100%;
	height: 48px;
	line-height: 48px;
	.filter-item {
		display: inline-block;
		vertical-align: middle;
		margin-bottom: 10px;
	}
	.kInput {
		position: absolute;
		right: 20px;
	}
	.filter-title {
		height: 48px;
		line-height: 48px;
		font-size: 16px;
		font-weight: 500;
		margin-right: 22px;
		color: #14162e;
	}
	.user-item {
		margin-left: 10px;
		margin-right: 20px;
	}
	.user-status,
	.account-status {
		margin-right: 20px;
	}
}
.top-btn {
	margin: 30px 0px 30px 0px;
	font-size: 14px;
	color: #ffffff;
	&:nth-of-type(2) {
		margin-left: 20px;
	}
	&:nth-of-type(3) {
		margin-left: 20px;
	}
	&:nth-of-type(4) {
		margin-left: 20px;
	}
	&:nth-of-type(5) {
		margin-left: 20px;
	}
}
.top-right-btn-container {
	position: relative;
	display: flex;
	.top-right-btn {
		position: absolute;
		right: 20px;
		top: 30px;
		background-color: #f8f7fb;
		border-color: transparent;
		color: #14162e;
		&:hover {
			color: #ffffff;
			background-color: $mainColor;
		}
		&:active {
			color: #14162e;
		}
	}
	.handle-main {
		display: flex;
		margin-left: 0px;
		.handle-item {
			display: flex;
			align-items: center;
			width: 250px;
			margin-left: 50px;
		}
	}
}
::v-deep .el-input__inner:focus {
	border-color: $mainColor;
}
.el-form-item__label-wrap .el-form-item__label {
	float: none;
}
.top-radio-group {
	margin-bottom: 40px;
}
.dialog-openboxsetting {
	display: flex;
	flex-direction: row;
	justify-content: center;
	margin: 80px 80px;
}

.form-modify {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	margin: 10px 80px;
	.modify-right {
		margin-left: 80px;
	}
	::v-deep .el-input__inner {
		// border-color: $mainColor;
		width: 200px;
	}
}
.give-dialog {
	::v-deep .el-dialog__body {
		width: 678px;
		text-align: center;
	}
	.give_div {
		margin: 0 auto;
		padding: 50px 0px;
		height: 400px;
	}
}
.addBox-dialog {
	::v-deep .el-dialog__body {
		width: 678px;
		padding: 10px 30px 30px 30px;
	}
	::v-deep .image-slot {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 100%;
		background: #f5f7fa;
		color: #909399;
		font-size: 40px;
	}
	::v-deep .el-select .el-select__tags > span {
		display: none;
	}
	.el-tag + .el-tag {
		margin-left: 10px;
	}
	.el-tag {
		color: $mainColor;
		background-color: #ffffff;
		border-color: $mainColor;
		::v-deep .el-tag__close {
			color: $mainColor;
		}
		::v-deep .el-icon-close:hover {
			color: #ffffff;
			background: $mainColor;
		}
	}
}
.upload-btn {
	font-size: 14px;
	color: #ffffff;
}
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}
.avatar {
	width: 178px;
	height: 178px;
	display: block;
}

.set_box {
	width: 700px;
	margin: 0 80px;
	box-sizing: border-box;
	.Recharge_Data {
		width: 100%;
		height: 40px;
		margin-top: 10px;
		margin-bottom: 30px;
		display: flex;
		align-items: center;
		.Recharge_Data_box {
			width: 100%;
			height: 40px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.el-input {
				width: 150px;
				height: 35px;
				input {
					width: 150px;
					height: 35px;
				}
			}
			span {
				font-size: 14px;
				width: 100px;
			}
		}
		.operation {
			width: 12%;
			display: flex;
			justify-content: space-between;
			.el-icon {
				&-circle-plus,
				&-remove {
					font-size: 22px;
					color: #3b425d;
					margin-left: 10px;
				}
			}
		}
	}
}
</style>
